package com.longtop.perform.khyg.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.LinkedMap;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.CacheUtil;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.BaseUncheckedException;
import com.longtop.framework.sys.codeInfo.model.TSysCodeInfo;
import com.longtop.framework.sys.file.excel.ExcelBean;
import com.longtop.framework.sys.file.excel.ExcelExtractor;
import com.longtop.framework.util.ArithUtil;
import com.longtop.framework.util.BeanUtil;
import com.longtop.framework.util.SpringBeanFactory;
import com.longtop.framework.util.StringUtil;
import com.longtop.intelliweb.action.IActionContext;
import com.longtop.intelliweb.common.Constants;
import com.longtop.intelliweb.view.Dataset;
import com.longtop.intelliweb.view.Field;
import com.longtop.intelliweb.view.Record;
import com.longtop.perform.khyg.model.TKhygIndex;
import com.longtop.perform.khyg.model.TKhygSegment;
import com.longtop.perform.khyg.model.TKhygTaskMx;

/**
 * 
 * @author 孙景弘
 * 
 */
public class TaskService extends BaseService {

	public static final String BEAN_ID = "taskService";

	/**
	 * 组装员工-指标(定量)任务明细DATASET
	 * 
	 * @param dataset_project_index
	 * @param dataset_task_user
	 * @param task
	 *            task=null：分配任务；task=view：任务查看；track：任务跟踪
	 */
	public void bulidUserDLIndexDataset(Dataset dataset_project_index, Dataset dataset_task_user, String task) {
		List<TKhygIndex> indexlist = BeanUtil.datasetToList(dataset_project_index, TKhygIndex.class);
		for (TKhygIndex projectIndex : indexlist) {
			// 获取指标单位：
			String indexUnit = projectIndex.getIndexUnit();
			List<TSysCodeInfo> indexUnitList = CacheUtil.getCodeInfoListByCodeTypeId("INDEX_UNIT");
			for (TSysCodeInfo TSysCodeInfo : indexUnitList) {
				if (TSysCodeInfo.getValue().equals(indexUnit)) {
					indexUnit = TSysCodeInfo.getContent();
					break;
				}
			}

			// 指标ID为fieldName 指标名称为filedLabel 。-fieldValue是员工任务对应的任务值taskValue
			String fieldName = projectIndex.getIndexId();
			if ("track".equals(task)) {
				dataset_task_user.addField(fieldName);
			} else {
				dataset_task_user.addField(fieldName, Constants.DataType_BIGDECIMAL);
				dataset_task_user.getField(fieldName).setMaxLength(14);
				dataset_task_user.getField(fieldName).setScale(2);// 小数位
			}
			dataset_task_user.getField(fieldName).setLabel(projectIndex.getIndexName() + "(" + indexUnit + ")");

		}
	}

	/**
	 * 保存员工任务明细
	 * 
	 * @param indexList
	 * @param taskUserRecordList
	 */
	public void saveUserTaskMx(List<TKhygIndex> indexList, List<Record> taskUserRecordList) {
		String segmentId = "";
		// 组装页面显示DATASET-到UserTaskMx：
		for (TKhygIndex userProjectIndex : indexList) {
			for (Record record : taskUserRecordList) {
				String taskId = record.getValue("taskId").toString();
				segmentId = record.getValue("segmentId").toString();
				String indexId = userProjectIndex.getIndexId();
				BigDecimal taskValue = (BigDecimal) record.getValue(indexId);// 员工任务对应的任务值taskValue

				// 取得相应的任务员工明细：
				List<TKhygTaskMx> tmpList = this.queryAll("from TKhygTaskMx where taskId = '" + taskId + "' and indexId = '" + indexId + "'");
				TKhygTaskMx userTaskMx = tmpList.get(0);

				// 只有在值不同时才执行更新：
				if (userTaskMx.getTaskValue() == null || taskValue == null || taskValue.doubleValue() != userTaskMx.getTaskValue().doubleValue()) {
					userTaskMx.setTaskValue(taskValue); // 设置指标和对应的任务值
					super.update(userTaskMx); // 更新员工任务明细:
				}
			}
		}
		// 修改相应考核分段表的进度状态:
		ProjectService projectService = SpringBeanFactory.getBean(ProjectService.BEAN_ID);
		projectService.updateSegmentStatus(TKhygSegment.class, segmentId, 4, true);
		projectService.updateSegmentStatus(TKhygSegment.class, segmentId, 6, false);// 计算成绩状态为0
	}

	/**
	 * 任务员工的明细（任务查看）
	 * 
	 * @param segmentId
	 * @param dataset_task_user
	 * @return
	 */
	public Dataset getUserTaskView(String segmentId, Dataset dataset_task_user, IActionContext context) {
		// 取得考核分段-任务对应的员工
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("segmentId", segmentId);
		if (context != null) {
			String userIdListStr = context.getElementValue("Text_userIdListStr");
			userIdListStr = StringUtil.afterOfDeletion(userIdListStr, ",");// 员工ID字符串，用逗号隔开
			queryMap.put("userIdListStr", userIdListStr);
		}

		this.queryForPageByIbatis("khygTaskSql.queryTaskUser", null, queryMap, dataset_task_user, false);

		// 取得考核分段-任务员工明细
		List<TKhygTaskMx> userTaskMxList = this.queryAll("from TKhygTaskMx where segmentId = '" + segmentId + "'");

		// 填充任务员工明细DATASET：
		List<Record> taskUserRecordList = dataset_task_user.getRecordList();
		for (Record record : taskUserRecordList) {
			for (TKhygTaskMx userTaskMx : userTaskMxList) {
				if (record.getValue("userId").equals(userTaskMx.getUserId()) && record.getValue("taskId").equals(userTaskMx.getTaskId())) {
					record.setValue(userTaskMx.getIndexId(), userTaskMx.getTaskValue());// 设置显示值为：任务值
				}
			}
		}
		return dataset_task_user;
	}

	/**
	 * 任务员工的明细（任务跟踪）
	 * 
	 * @param segmentId
	 * @param dataset_task_user
	 * @return
	 */
	public Dataset getUserTaskTrack(String segmentId, Dataset dataset_task_user) {
		// 取得考核分段-任务对应的员工
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("segmentId", segmentId);
		this.queryForPageByIbatis("khygTaskSql.queryTaskUser", null, queryMap, dataset_task_user, false);
		// 取得考核分段-任务员工明细( 包括完成值 )
		List<TKhygTaskMx> userTaskMxList = this.queryForListByIbatis("khygTaskSql.queryTaskUserMxWithFinishValue", segmentId);

		// 填充任务员工明细DATASET：
		List<Record> taskUserRecordList = dataset_task_user.getRecordList();

		for (Record record : taskUserRecordList) {
			for (TKhygTaskMx userTaskMx : userTaskMxList) {
				if (record.getValue("userId").equals(userTaskMx.getUserId()) && record.getValue("taskId").equals(userTaskMx.getTaskId())) {
					// 设置显示值为：任务值；完成值；完成率
					DecimalFormat decimalFormat = new DecimalFormat("#,###.######");
					String taskValue = userTaskMx.getTaskValue() == null ? "0" : decimalFormat.format(userTaskMx.getTaskValue().doubleValue());
					String finishValue = userTaskMx.getIndexValue() == null ? "0" : decimalFormat.format(userTaskMx.getIndexValue().doubleValue());

					String percentStr = "";
					if (userTaskMx.getTaskValue() != null && userTaskMx.getIndexValue() != null) {
						double percent = ArithUtil.div(userTaskMx.getIndexValue().doubleValue(), userTaskMx.getTaskValue().doubleValue(), 2);
						percentStr = String.valueOf(percent);
					}

					String displayValue = "任务值:" + taskValue + "" + " | 完成值:" + finishValue + " ";
					record.setValue(userTaskMx.getIndexId(), displayValue);
				}
			}
		}
		return dataset_task_user;
	}

	/**
	 * 导出员工任务查看Excel
	 * 
	 * @param dataset_project_index
	 * @param segmentId
	 * @param isEmptyData
	 *            是否是需要带数据
	 * @param context
	 * @throws BaseUncheckedException
	 * @throws IOException
	 */
	public void exportTaskView(Dataset dataset_project_index, String segmentId, boolean isEmptyData, IActionContext context) throws BaseUncheckedException, IOException {
		// 构建 excel头部：
		Map<String, Object> excelHeadMap = new LinkedMap();
		excelHeadMap.put("userId", "员工ID");
		excelHeadMap.put("userName", "员工姓名");
		excelHeadMap.put("orgName", "所属机构");

		List<TKhygIndex> indexlist = BeanUtil.datasetToList(dataset_project_index, TKhygIndex.class);
		for (TKhygIndex projectIndex : indexlist) {
			// 获取指标单位：
			String indexUnit = projectIndex.getIndexUnit();
			List<TSysCodeInfo> indexUnitList = CacheUtil.getCodeInfoListByCodeTypeId("0003");
			for (TSysCodeInfo TSysCodeInfo : indexUnitList) {
				if (TSysCodeInfo.getValue().equals(indexUnit)) {
					indexUnit = TSysCodeInfo.getContent();
					break;
				}
			}
			excelHeadMap.put(projectIndex.getIndexId(), projectIndex.getIndexName() + "(" + indexUnit + ")");// 指标名称表头
		}

		// 构建excel单元格值：
		List<Map<String, Object>> valueMapList = new ArrayList<Map<String, Object>>();

		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("segmentId", segmentId);
		List<Map<String, Object>> taskUserList = this.queryForListByIbatis("khygTaskSql.queryTaskUser", queryMap); // 取得考核分段-任务对应的员工
		List<TKhygTaskMx> userTaskMxList = this.queryForListByIbatis("khygTaskSql.queryTaskUserMx", segmentId); // 取得考核分段-任务员工明细

		Map<String, Object> valueMap;
		for (Map<String, Object> map : taskUserList) {
			valueMap = new LinkedMap();
			valueMap.put("userId", map.get("userId"));
			valueMap.put("userName", map.get("userName"));
			valueMap.put("orgName", map.get("orgName"));
			if (!isEmptyData) {
				for (TKhygTaskMx userTaskMx : userTaskMxList) {
					if (map.get("userId").equals(userTaskMx.getUserId()) && map.get("taskId").equals(userTaskMx.getTaskId())) {
						valueMap.put(userTaskMx.getIndexId(), userTaskMx.getTaskValue());// 设置任务值
					}
				}
			}
			valueMapList.add(valueMap);
		}

		ExcelBean excelBean = new ExcelBean("TASK_VIEW_LIST", "员工任务查看表");
		excelBean.setExcelHeadMap(excelHeadMap);

		ExcelExtractor excutor = new ExcelExtractor(excelBean);
		excutor.exportExcel(valueMapList, context);

	}

	/**
	 * 导出员工任务跟踪excel
	 * 
	 * @param dataset_project_index
	 * @param segmentId
	 * @param context
	 * @throws BaseUncheckedException
	 * @throws IOException
	 */
	public void exportTaskTrack(Dataset dataset_project_index, String segmentId, IActionContext context) throws BaseUncheckedException, IOException {
		// 构建excel头部：
		Map<String, Object> excelHeadMap = new LinkedMap(); // excel头部
		Map<String, Integer> groupColumn = new LinkedMap();// 合并单元格excel头部
		groupColumn.put("员工明细", 2);
		excelHeadMap.put("userId", "员工ID");
		excelHeadMap.put("userName", "员工姓名");
		excelHeadMap.put("orgName", "所属机构");

		List<TKhygIndex> indexlist = BeanUtil.datasetToList(dataset_project_index, TKhygIndex.class);
		for (TKhygIndex projectIndex : indexlist) {
			// 获取指标单位：
			String indexUnit = projectIndex.getIndexUnit();
			List<TSysCodeInfo> indexUnitList = CacheUtil.getCodeInfoListByCodeTypeId("0003");
			for (TSysCodeInfo TSysCodeInfo : indexUnitList) {
				if (TSysCodeInfo.getValue().equals(indexUnit)) {
					indexUnit = TSysCodeInfo.getContent();
					break;
				}
			}
			groupColumn.put(projectIndex.getIndexName() + "(" + indexUnit + ")", 2);// 指标名称表头
		}

		// 构建excel单元格值：
		List<Map<String, Object>> valueMapList = new ArrayList<Map<String, Object>>();

		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("segmentId", segmentId);
		List<Map<String, Object>> taskUserList = this.queryForListByIbatis("khygTaskSql.queryTaskUser", queryMap); // 取得考核分段-任务对应的员工
		List<TKhygTaskMx> userTaskMxList = this.queryForListByIbatis("khygTaskSql.queryTaskUserMxWithFinishValue", segmentId); // 取得考核分段-任务员工明细( 包括完成值 )

		Map<String, Object> valueMap;
		for (Map<String, Object> map : taskUserList) {
			valueMap = new LinkedMap();
			valueMap.put("userId", map.get("userId"));
			valueMap.put("userName", map.get("userName"));
			valueMap.put("orgName", map.get("orgName"));
			for (TKhygTaskMx userTaskMx : userTaskMxList) {
				if (map.get("userId").equals(userTaskMx.getUserId()) && map.get("taskId").equals(userTaskMx.getTaskId())) {
					excelHeadMap.put(userTaskMx.getIndexId() + "taskValue", "任务值");
					excelHeadMap.put(userTaskMx.getIndexId() + "finishValue", "完成值");
					// 设置显示值为：任务值；完成值；
					valueMap.put(userTaskMx.getIndexId() + "taskValue", userTaskMx.getTaskValue());
					valueMap.put(userTaskMx.getIndexId() + "finishValue", userTaskMx.getIndexValue());
				}
			}
			valueMapList.add(valueMap);
		}

		ExcelBean excelBean = new ExcelBean("TASK_TRACK_LIST", "员工任务跟踪表");
		excelBean.setExcelHeadMap(excelHeadMap);
		excelBean.setGroupColumn(groupColumn);

		ExcelExtractor excutor = new ExcelExtractor(excelBean);
		excutor.exportExcel(valueMapList, context);
	}

	/**
	 * 显示导入excel数据-员工任务
	 * 
	 * @param segmentId
	 * @param dataset_task_user
	 * @param userTaskMapList
	 * @throws BaseCheckedException
	 */
	public void getUserTaskFromImport(String segmentId, Dataset dataset_task_user, List<Map> userTaskMapList) throws BaseCheckedException {
		// 取得考核分段-任务对应的员工
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("segmentId", segmentId);
		this.queryForPageByIbatis("khygTaskSql.queryTaskUser", null, queryMap, dataset_task_user, false);

		List<Record> recordList = dataset_task_user.getRecordList();
		List<Field> fieldList = dataset_task_user.getFieldList();
		for (Record record : recordList) {
			String userId = record.getValue("userId").toString();
			for (Map map : userTaskMapList) {
				if (map.containsKey("员工ID")) {
					if (!map.get("员工ID").toString().equals(userId)) {
						continue;// 跳过匹配不到记录员工ID的循环
					}
					for (Field field : fieldList) {
						if (field.getDataType().equals("string")) {
							continue;// 跳过不需要赋值的字段
						}
						if (map.containsKey(field.getLabel())) {
							try {
								BigDecimal decimalValue = new BigDecimal(String.valueOf(map.get(field.getLabel())));
								record.setValue(field.getName(), decimalValue);
							} catch (Exception e) {
								record.setValue(field.getName(), null);
								throw new BaseCheckedException("EXCEL读写错误，导入文件中员工ID为【" + userId + "】的指标【" + field.getLabel() + "】不是有效的数字类型。");
							}
						} else {
							throw new BaseCheckedException("EXCEL读写错误，导入文件缺少列【" + field.getLabel() + "】。");
						}
					}
				} else {
					throw new BaseCheckedException("EXCEL读写错误，导入的文件缺少列【员工ID】。");
				}

			}
		}
	}
}
